package com.weiaibenpao.demo.chislim.sport;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.google.gson.Gson;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.RunningPreferences;
import com.weiaibenpao.demo.chislim.RunningService;
import com.weiaibenpao.demo.chislim.RunningUtils;
import com.weiaibenpao.demo.chislim.bean.AddSportsBean;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.db.model.RunningRecord;
import com.weiaibenpao.demo.chislim.model.MyModel;
import com.weiaibenpao.demo.chislim.sport.bean.MarathonreatetimeBean;
import com.weiaibenpao.demo.chislim.sport.utils.PolyLines;
import com.weiaibenpao.demo.chislim.sport.view.MarathonDataView;
import com.weiaibenpao.demo.chislim.ui.BaseRunningActivity;
import com.weiaibenpao.demo.chislim.ui.MusicTypeActivity;
import com.weiaibenpao.demo.chislim.util.SlideUnlockView;
import com.weiaibenpao.demo.chislim.util.SpeechUtil;
import com.weiaibenpao.demo.chislim.util.Utils;
import com.weiaibenpao.demo.chislim.util.VoicePlayerUtil;

import org.litepal.crud.DataSupport;
import org.litepal.crud.callback.FindMultiCallback;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.weiaibenpao.demo.chislim.RunningService.CALORIE;
import static com.weiaibenpao.demo.chislim.RunningService.FINISH;
import static com.weiaibenpao.demo.chislim.RunningService.PAUSE;
import static com.weiaibenpao.demo.chislim.RunningService.RUNNING;
import static com.weiaibenpao.demo.chislim.RunningService.STEP;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.CITY_CODE;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.ISFIRSTCOME;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.IS_OVER;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_DISTANCE;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_ID;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_TITLE;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_TYPE;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MATCH_END_TIME;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MATCH_START_TIME;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.REST_TIME;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.RUN_DIS;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.SELECT_NAME;

public class MarathonActivity extends BaseRunningActivity implements RunningService.OnDataUpdatedListener {


    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.music_tv)
    TextView musicTv;
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.marathon_data_view)
    MarathonDataView marathonDataView;
    @BindView(R.id.lock)
    ImageView lock;
    @BindView(R.id.start)
    ImageView start;
    @BindView(R.id.countdown_view)
    TextView countdownView;
    @BindView(R.id.lock_layout)
    View lock_layout;
    @BindView(R.id.marathon_total_dis)
    TextView tv_marathonTotalDis;
    @BindView(R.id.marathon_rest_dis)
    TextView tv_marathonRestDis;
    @BindView(R.id.marathon_rest_time)
    TextView tv_marathonRestTime;
    @BindView(R.id.marathon_my_dis)
    TextView marathonMyDis;
    @BindView(R.id.marathon_my_time)
    TextView marathonMyTime;
    @BindView(R.id.slideUnlockView)
    SlideUnlockView slideUnlockView;
    @BindView(R.id.mask)
    View mask;
    @BindView(R.id.location_tv)
    TextView locationTv;
    @BindView(R.id.root)
    RelativeLayout root;
    private Context context;
    RunningService mService;
    public static final String TYPE_USER_LAUNCHED_MATCH ="8";
    private static final String TYPE_MARATHON ="马拉松";
    private static final String TYPE_EVENT ="活动";
    private String matchType;
    private AMap aMap;
    private boolean isFirstRun = true;//
    private VoicePlayerUtil voicePlayerUtil;
    private SharedPreferences mSharedPreferences;
    private String marathon_id = "0";
    private String sport_type;
    private String code;
    private float myRunDis = 0.0f;
    private int myRunTime = 0;
    private final int TIMER_TASK = 1022;
    private Timer timer = new Timer();
    private String marathon_endTime;//马拉松结束时间
    private String title = null;
    private long restTime;//马拉松总时间
    private PolyLines polyLines;
    private float runDis;//马拉松已跑总里程
    private String selectName;
    private String mStep = "0";
    private String mCalorie = "0";

    private StringBuilder mFrequencyPhoto = new StringBuilder("");   //步频图
    private StringBuilder mStridePhoto = new StringBuilder("");      //步幅图
    private StringBuilder mPaceForm = new StringBuilder("");         //配速列表
    private StringBuilder mAltitudePhoto = new StringBuilder();    //海拔图
    private StringBuilder mLocusPhoto = new StringBuilder();       //轨迹
    private ArrayList<LatLng> mLatLngList = new ArrayList<>();
    private double marathonTotalDis;//马拉松总里程
    private LatLng latLng;
    private PolylineOptions polylineOption2;
    private PolylineOptions polylineOption;
    private int runNum;
    private int num;
    private RunningPreferences preferences;
    private long currentTime;
    DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private boolean isFirstMaker = true;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TIMER_TASK:

                    break;
                case PolyLines.POLYLINE_OVER_SUCCESS:
                    polylineOption = ((PolylineOptions) msg.obj);
                    num = polylineOption.getPoints().size();
                    if (polylineOption != null && polylineOption.getPoints().size() > 0) {
                        if (isFirstMaker) {
                            setMarkView(polylineOption.getPoints().get(0));
                            drawTrace((int) runDis);
                        }
                    }
                    break;
            }
        }
    };
    private boolean isOver = false;
    private int WRITE_COARSE_LOCATION_REQUEST_CODE = 0;
    private boolean isFirstCome = true;//第一次进来
    private String marathon_startTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_marathon);
        ButterKnife.bind(this);
        context = new WeakReference<Activity>(this).get();
//        checkPermissions();

        getIntentData();
        initService();
        preferences = RunningPreferences.getInstance();
        int state = preferences.getRunningState();
        if (state == RunningService.RUNNING || state == PAUSE) {
            lock.setVisibility(View.VISIBLE);
            start.setVisibility(View.GONE);
            restoreDataDisplay();//由于服务端的回调有过滤，例如如果精度不满足，就不回调，所以这里进行一次手动恢复现场

        }

        mapView.onCreate(savedInstanceState);
        initMap();
        initLockView();


    }

    @Override
    public void checkPerMissions() {
        super.checkPerMissions();
    }

    private void initLockView() {
        slideUnlockView.setOnUnLockListener(new SlideUnlockView.OnUnLockListener() {
            @Override
            public void setUnLocked(boolean unLocked) {
                if (unLocked) {
                    mask.setVisibility(View.GONE);
                    slideUnlockView.reset();
                    slideUnlockView.setVisibility(View.GONE);
                    lock.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void restoreDataDisplay() {
        showAddToWhiteListNotice();
        marathon_id = preferences.getString(MARATHON_ID);
        sport_type = preferences.getString(MARATHON_TYPE);
        code = preferences.getString(CITY_CODE);
        marathon_endTime = preferences.getString(MATCH_END_TIME);
//        marathon_startTime=preferences.getString(MATCH_START_TIME);
        title = preferences.getString(MARATHON_TITLE);
        selectName = preferences.getString(SELECT_NAME);
        myRunTime = preferences.getRunningTime();
        myRunDis = preferences.getRunningDistance() / 1000;
        if(TextUtils.isEmpty(preferences.getString(MARATHON_DISTANCE))){
            marathonTotalDis = 0;
        }else {
            marathonTotalDis = Double.parseDouble(preferences.getString(MARATHON_DISTANCE));
        }
        runDis = preferences.getFloat(RUN_DIS);
        marathonMyDis.setText(decimalFormat.format(myRunDis));
        tv_marathonRestDis.setText(decimalFormat.format((marathonTotalDis - runDis)));
        marathonMyTime.setText(RunningUtils.getHmsTime((myRunTime)));
        tv_marathonTotalDis.setText(decimalFormat.format(runDis));
        restTime = preferences.getLong(REST_TIME);
        tv_marathonRestTime.setText(RunningUtils.getHmsTime((int) (restTime / 1000)));
        isOver = preferences.getBoolean(IS_OVER);
        mCalorie = preferences.getString(CALORIE);
        mStep = preferences.getString(STEP);
        isFirstCome = preferences.getBoolean(ISFIRSTCOME);
        initMatchType();

    }


    private void getIntentData() {
//        voicePlayerUtil = new VoicePlayerUtil(this);

        if (getIntent() != null) {
            marathon_id = getIntent().getStringExtra(MARATHON_ID);
            sport_type = getIntent().getStringExtra(MARATHON_TYPE);
            code = getIntent().getStringExtra(CITY_CODE);
            marathon_endTime = getIntent().getStringExtra(MATCH_END_TIME);
            marathon_startTime = getIntent().getStringExtra(MATCH_START_TIME);
            title = getIntent().getStringExtra(MARATHON_TITLE);
            selectName = getIntent().getStringExtra(SELECT_NAME);
            if (!TextUtils.isEmpty(getIntent().getStringExtra(MARATHON_DISTANCE))) {
                marathonTotalDis = Float.parseFloat(getIntent().getStringExtra(MARATHON_DISTANCE));
            }
            if (!TextUtils.isEmpty(title)) {
                titleTv.setText(title);
            }
            if (!TextUtils.isEmpty(marathon_endTime) && !TextUtils.isEmpty(marathon_startTime)) {
                restTime = Long.parseLong(marathon_endTime) - Long.parseLong(marathon_startTime);
            }
            initMatchType();

            if(!TextUtils.isEmpty(marathon_id)){
                RunningPreferences.getInstance().putString(MARATHON_ID,marathon_id);
                RunningPreferences.getInstance().putString(MARATHON_TYPE, sport_type);
                RunningPreferences.getInstance().putString(CITY_CODE, code);
                RunningPreferences.getInstance().putString(MATCH_END_TIME, marathon_endTime);
                RunningPreferences.getInstance().putString(MATCH_START_TIME,marathon_startTime);
                RunningPreferences.getInstance().putString(MARATHON_TITLE, title);
                RunningPreferences.getInstance().putString(SELECT_NAME, selectName);
                RunningPreferences.getInstance().putString(MARATHON_DISTANCE, getIntent().getStringExtra(MARATHON_DISTANCE));
            }
        }

    }

    private void initMatchType() {
        if(TYPE_USER_LAUNCHED_MATCH.equals(sport_type)){
            matchType = TYPE_EVENT;
        }else {
            matchType = TYPE_MARATHON;
        }
    }


    private void getMarathon(float everyDis) {
        apiStores.getMarathonData(UserBean.getUserBean().userId, Integer.parseInt(marathon_id), everyDis, mStep).enqueue(new Callback<MarathonreatetimeBean>() {
            @Override
            public void onResponse(Call<MarathonreatetimeBean> call, Response<MarathonreatetimeBean> response) {
                if (response.body() != null) {
                    Log.e("lyf222", "response: " + new Gson().toJson(response));
                    if (response.body().getCode() == 0) {
                        String totalDistance = response.body().getData().getUserTotalDistance();
                        runDis = Float.parseFloat(totalDistance);
                        restTime = response.body().getData().getRestTime();
                        preferences.putFloat(RUN_DIS, runDis);
                        tv_marathonRestDis.setText(response.body().getData().getNextDistance());
                        tv_marathonTotalDis.setText(totalDistance);
                        drawTrace((int) runDis);
                        if (restTime <= 600000 && isFirstRun) {//比赛小于10分钟
//                            voicePlayerUtil.startVoice("距离比赛结束已不足10分钟，团队已跑" + runDis + "公里，剩余+" + tv_marathonRestDis.getText().toString() + "公里，继续加油");
                            SpeechUtil.getInstance().speak("距离比赛结束已不足10分钟，团队已跑" + runDis + "公里，剩余+" + tv_marathonRestDis.getText().toString() + "公里，继续加油");
                            isFirstRun = false;
                        }
                    } else if (response.body().getCode() == 1) {

//                        voicePlayerUtil.startVoice(response.body().getMsg());
                        SpeechUtil.getInstance().speak(response.body().getMsg());
                        uploadRunningData();
                        isOver = true;
                        if (mService != null) mService.setState(PAUSE);
                        preferences.putBoolean(IS_OVER, isOver);
                    }
                }
            }

            @Override
            public void onFailure(Call<MarathonreatetimeBean> call, Throwable throwable) {

            }
        });
    }


    private void initMap() {

        if (aMap == null) {
            aMap = mapView.getMap();
        }
        if (!TextUtils.isEmpty(title)) {
            titleTv.setText(title);
        }
        polyLines = new PolyLines(context, aMap);
        polyLines.drawLIne(code, selectName, mHandler);
        if (polylineOption2 == null) {
            polylineOption2 = new PolylineOptions();
            polylineOption2.width(12).color(Color.parseColor("#7a2075"));
        }
        timer.schedule(new MyTimerTask(), 1000, 1000);
        //第一次进来弹框
        if (isFirstCome) {
            isFirstCome = false;
            preferences.putBoolean(ISFIRSTCOME, isFirstCome);
            showStartDialog();
        }
        if (isOver) {
            timer.cancel();
            uploadRunningData();
        } else {
            getMarathon(myRunDis);
        }

    }


    private void showStartDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = LayoutInflater.from(this).inflate(R.layout.marathon_start, null);
        TextView city = (TextView) view.findViewById(R.id.tv_title_marathon);
        city.setText(title);
        view.findViewById(R.id.start_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (goEnableGPS()) return;
                if (mService != null) {
                    startCountdown();
                    dialog.dismiss();
                }
            }
        });
        dialog.setView(view);
        dialog.show();
    }

    private void initService() {
        Intent serviceIntent = new Intent(MarathonActivity.this, RunningService.class);
        serviceIntent.putExtra(RunningService.RUNNING_ACTIVITY, getClass().getCanonicalName());
        serviceIntent.putExtra(RunningService.NEED_SAVE_TRACE, true);
        serviceIntent.putExtra(RunningService.NEED_EXTRA_DATA, true);
        serviceIntent.putExtra(RunningService.NEED_SAVE_STATE, true);
        startService(serviceIntent);
        bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 获取服务对象
     */
    private ServiceConnection connection = new ServiceConnection() {


        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            RunningService.LocalBinder builder = (RunningService.LocalBinder) service;
            mService = builder.getService();
            mService.registerOnDataUpdatedListener(MarathonActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };

    @OnClick({R.id.marathon_data_view, R.id.lock, R.id.start, R.id.countdown_view, R.id.music_tv,R.id.marathon_giveUp})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.marathon_data_view:
                break;
            case R.id.lock:
                lock.setVisibility(View.GONE);
                slideUnlockView.setVisibility(View.VISIBLE);
                mask.setVisibility(View.VISIBLE);
                break;
            case R.id.start:
                if (goEnableGPS()) return;
                if (mService != null) {
                    startCountdown();
                }

                break;
            case R.id.countdown_view:
                break;
            case R.id.music_tv:
                Intent intent = new Intent(this, MusicTypeActivity.class);
                startActivity(intent);
                break;
            case R.id.marathon_giveUp:
                doFinish();
                break;
        }
    }

    /**
     * 开始跑步
     */
    int runCount;

    private void startCountdown() {
        countdownView.setVisibility(View.VISIBLE);
        isFirstCome = false;
        preferences.putBoolean(ISFIRSTCOME, isFirstCome);
        //倒计时3秒
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 3; i >= -1; i--) {
                    runCount = i;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (runCount > 0) {
//                                voicePlayerUtil.startVoice(runCount + "");
                                SpeechUtil.getInstance().speak(String.valueOf(runCount));
                                countdownView.setText(runCount + "");

                            } else if (runCount == 0) {
                                countdownView.setText("GO!");
//                                voicePlayerUtil.startVoice("跑步开始");
                                SpeechUtil.getInstance().speak("跑步开始");
                                mService.setState(RunningService.RUNNING);
                                getMarathon(myRunDis);
                            } else {
                                start.setVisibility(View.GONE);
                                countdownView.setVisibility(View.GONE);
                                lock.setVisibility(View.VISIBLE);
                            }
                        }
                    });

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
    }


    /**
     * 事实刷新数据
     *
     * @param data
     */
    @Override
    public void onDataUpdated(Bundle data) {

        myRunDis = data.getFloat(RunningService.DISTANCE) / 1000;
        marathonMyDis.setText(decimalFormat.format(myRunDis));
        mStep = data.getString(STEP);
        mCalorie = data.getString(CALORIE);
        Log.e("wlx", "myRunDis: " +  myRunDis);


    }

    /**
     * @param runningTime
     */
    @Override
    public void onRunningTime(final int runningTime) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                marathonMyTime.setText(RunningUtils.getHmsTime(runningTime));
                myRunTime = runningTime;
                if (myRunTime % 15 == 0) {
                    if (!Utils.isNetWorkConnected()) {
                        Toast.makeText(context, "请连接网络，以保证实时数据共享", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    getMarathon(myRunDis);
                }
            }
        });
    }


    private void drawTrace(int runDis) {
        int h;
        if (polylineOption2.getPoints() != null) {
            polylineOption2.getPoints().clear();
        }
        if (polylineOption != null) {
            if (runDis < marathonTotalDis) {
                h = (int) (num * (runDis / marathonTotalDis));
                if (h == num) {
                    h = num - 1;
                }
                for (int m = runNum; m <= h; m++) {
                    //updateCamera(((LatLng)arrayList.get(m)).latitude,((LatLng)arrayList.get(m)).longitude);            //设置地图中心点
                    polylineOption2.add(polylineOption.getPoints().get(m));

                }
                aMap.addPolyline(polylineOption2);
                runNum = h;
            }


        }

    }

    private void setMarkView(LatLng latLng) {
        View view = View.inflate(context, R.layout.mark_layout, null);
        TextView sportMark = (TextView) view.findViewById(R.id.sportTitle);
        sportMark.setText("起");
        Bitmap bitmap = convertViewToBitmap(view);
        drawMarkerOnMap(latLng, bitmap, String.valueOf("起"));
        isFirstMaker = false;
    }

    private Bitmap convertViewToBitmap(View view) {

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

        view.buildDrawingCache();

        return view.getDrawingCache();
    }

    private Marker drawMarkerOnMap(LatLng point, Bitmap markerIcon, String id) {

        if (aMap != null && point != null) {

            return aMap.addMarker(new MarkerOptions().anchor(0.5f, 1)
                    .position(point)
                    .title(id)
                    .icon(BitmapDescriptorFactory.fromBitmap(markerIcon)));
        }
        return null;
    }

    private boolean alreadyAssembled;

    private void uploadRunningData() {
        showProgressDialog();
        if (alreadyAssembled) {
            upLoadData();
        } else {
            DataSupport.findAllAsync(RunningRecord.class).listen(new FindMultiCallback() {
                @Override
                public <T> void onFinish(List<T> list) {
                    if (!isDestroyed()) {
                        assembleDataFromDatabase((List<RunningRecord>) list);
                        alreadyAssembled = true;
                        upLoadData();
                    }
                }
            });
        }
    }

    private void assembleDataFromDatabase(List<RunningRecord> list) {
        List<RunningRecord> records = list;
        for (int i = 0; i < records.size(); i++) {
            RunningRecord record = records.get(i);
            mLocusPhoto.append(String.valueOf(record.getLng())).append(":").append(String.valueOf(record.getLat())).append(":").append(record.getSpeed()).append(",");
            //Log.e("assemble--json",new Gson().toJson(record));//这个打印很耗时  而且还有个坑，单引号和双引号会显示乱码
            String timeStr = String.valueOf(record.getTime());
            mFrequencyPhoto.append(timeStr).append(":").append(record.getFrequency()).append(",");
            mStridePhoto.append(timeStr).append(":").append(record.getStride()).append(",");
            if (!TextUtils.isEmpty(record.getKmPace())) {
                mPaceForm.append(record.getKmValue()).append(":").append(record.getKmPace()).append(":").append(timeStr).append(",");
            }
            mAltitudePhoto.append(timeStr).append(":").append(record.getAltitude()).append(",");
        }
        Log.e("上传的数据", "坐标--" + mLocusPhoto.toString() + "\n" + "步频--" + mFrequencyPhoto.toString() + "\n" + " 步幅--" + mStridePhoto.toString() + "\n" + "   配速--" + mPaceForm.toString() + "\n" + "  海拔--" + mAltitudePhoto);

    }

    /**
     * 提交跑步记录
     */
    public void upLoadData() {

        if (!Utils.isNetWorkConnected()) {
            Toast.makeText(context, "亲，网络连接失败", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (TextUtils.isEmpty(mStep)){
//            mStep="0";
//        }
//        if (TextUtils.isEmpty(mCalorie)){
//            mCalorie="0";
//        }
        MyModel.getModel().getService().addMarathon(UserBean.getUserBean().userId, Integer.parseInt(sport_type),
                marathon_id, myRunTime,
                myRunDis + "",
                mCalorie, mStep,
                String.valueOf(mAltitudePhoto), String.valueOf(mFrequencyPhoto), String.valueOf(mStridePhoto),
                String.valueOf(mPaceForm), String.valueOf(mLocusPhoto)).enqueue(new Callback<AddSportsBean>() {
            @Override
            public void onResponse(Call<AddSportsBean> call, Response<AddSportsBean> response) {
                Log.e("wlx", "AddSportsBean: " + new Gson().toJson(response));
//                mService.setState(FINISH);
                if (response.body() != null) {
                    AddSportsBean.DataBean dataBean = response.body().getData();
                    if(dataBean != null){
                        boolean isFinished = TextUtils.equals(getString(R.string.yes_en),dataBean.getIsFinish());
                        SportRecordShareActivity.openActivity(context, dataBean.getUrl(), String.valueOf(titleTv.getText()),true,isFinished);
                    }

                    doFinish();
                } else
                    doFinish();
            }

            @Override
            public void onFailure(Call<AddSportsBean> call, Throwable throwable) {
                doFinish();
            }
        });
        dismissProgressDialog();


    }

    private void doFinish() {
        timer.cancel();
        if (mService != null) mService.setState(FINISH);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();

        if (mService != null) {
            mService.unRegisterOnDataUpdatedListener();

        }
        if (connection != null)
            unbindService(connection);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }


    private void showUploadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("跑步提示");
        builder.setMessage("是否保存并上传数据？");
        builder.setNegativeButton("放弃", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mService.setState(FINISH);
                finish();
            }
        });
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                uploadRunningData();
            }
        });
        builder.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mService != null && mService.getRunningState() == RUNNING) {
//                showUploadDialog();
                Toast.makeText(context, matchType+"已经开始，不能结束！", Toast.LENGTH_SHORT).show();
            } else if (isOver) {
                showUploadDialog();
            } else
                finish();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mapView.onSaveInstanceState(outState);
    }

    private long getTotalRestTime() {
        return restTime -= 1000;
    }

    @OnClick(R.id.marathon_giveUp)
    public void onViewClicked() {
    }


    class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            final long totalRestTime = getTotalRestTime();
            preferences.putLong(REST_TIME, totalRestTime);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_marathonRestTime.setText(RunningUtils.getHmsTime((int) (totalRestTime / 1000)));
                    if (totalRestTime <= 600000 && isFirstRun) {//比赛小于10分钟
//                        voicePlayerUtil.startVoice("距离比赛结束已不足10分钟，团队已跑" + runDis + "公里，剩余+" + tv_marathonRestDis.getText().toString() + "公里，继续加油");
                        SpeechUtil.getInstance().speak("距离比赛结束已不足10分钟，团队已跑" + runDis + "公里，剩余+" + tv_marathonRestDis.getText().toString() + "公里，继续加油");
                        isFirstRun = false;
                    }
                    if (totalRestTime <= 0) {
                        isOver = true;
                        timer.cancel();
                        tv_marathonRestTime.setText("00:00:00");
                        preferences.putBoolean(IS_OVER, isOver);
                        if (mService != null) mService.setState(RunningService.PAUSE);
//                        voicePlayerUtil.startVoice("马拉松比赛时间到");
                        SpeechUtil.getInstance().speak(matchType+"比赛时间到");
                        uploadRunningData();
                    }
                }
            });
        }
    }

    @Override
    public void onGPSStateChanged(boolean enabled) {
        if(!enabled){
            Toast.makeText(this,"GPS定位已关闭",Toast.LENGTH_LONG).show();
        }
    }
}
